<template>
  <div class="post-list">
    <el-card v-loading="loading">
      <div class="post-item" v-for="post in posts" :key="post.id">
        <div class="post-header">
          <span class="username">{{ post.username }}</span>
          <span class="time">{{ formatDateTime(post.createTime) }}</span>
        </div>
        <div class="post-content">{{ post.content }}</div>
        <div class="post-image" v-if="post.imageUrl">
          <el-image 
            :src="post.imageUrl" 
            :preview-src-list="[post.imageUrl]"
            fit="cover"
            @error="handleImageError(post)">
            <div slot="error" class="image-error">
              <i class="el-icon-picture-outline"></i>
              <span>图片加载失败</span>
            </div>
          </el-image>
        </div>
        <div class="post-actions">
          <el-button 
            :type="post.isLiked ? 'primary' : 'default'"
            size="small"
            @click="handleLike(post)">
            <i class="el-icon-star-on"></i>
            {{ post.likeCount }}
          </el-button>
          <el-button 
            size="small"
            @click="showComments(post)">
            <i class="el-icon-chat-line-square"></i>
            {{ post.commentCount }}
          </el-button>
        </div>
      </div>

      <!-- 评论对话框 -->
      <el-dialog 
        title="评论" 
        :visible.sync="commentDialogVisible"
        width="50%">
        <div class="comment-form">
          <el-input
            v-model="commentContent"
            type="textarea"
            :rows="3"
            placeholder="请输入评论内容">
          </el-input>
          <el-button 
            type="primary"
            @click="submitComment"
            style="margin-top: 10px">
            发表评论
          </el-button>
        </div>

        <div class="comment-list">
          <div 
            class="comment-item"
            v-for="comment in comments"
            :key="comment.id">
            <div class="comment-user">{{ comment.username }}</div>
            <div class="comment-content">{{ comment.content }}</div>
            <div class="comment-time">{{ formatDateTime(comment.createTime) }}</div>
          </div>
        </div>

        <el-pagination
          @current-change="handleCommentPageChange"
          :current-page.sync="commentPage.current"
          :page-size="commentPage.size"
          :total="commentPage.total"
          layout="prev, pager, next">
        </el-pagination>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'PostList',
  data() {
    return {
      loading: false,
      posts: [],
      currentPost: null,
      commentDialogVisible: false,
      commentContent: '',
      comments: [],
      commentPage: {
        current: 1,
        size: 10,
        total: 0
      }
    }
  },
  created() {
    this.fetchPosts()
  },
  methods: {
    async fetchPosts() {
      this.loading = true
      try {
        const res = await this.$http.get('/api/posts/list')
        this.posts = res.data.data.records.map(post => ({
          ...post,
          isLiked: Boolean(post.isLiked)
        }))
      } catch (error) {
        console.error('Error fetching posts:', error)
        this.$message.error('获取内容列表失败')
      } finally {
        this.loading = false
      }
    },

    async handleLike(post) {
      if (!this.checkLogin()) return

      try {
        const res = await this.$http.post(`/api/posts/like/${post.id}`)
        if (res.data.code === 200) {
          post.isLiked = !post.isLiked
          post.likeCount += post.isLiked ? 1 : -1
          this.$message.success(post.isLiked ? '点赞成功' : '取消点赞成功')
        }
      } catch (error) {
        this.$message.error('操作失败')
      }
    },

    async showComments(post) {
      this.currentPost = post
      this.commentDialogVisible = true
      this.commentPage.current = 1
      await this.fetchComments()
    },

    async fetchComments() {
      try {
        const res = await this.$http.get(`/api/posts/comments/${this.currentPost.id}`, {
          params: {
            pageNum: this.commentPage.current,
            pageSize: this.commentPage.size
          }

        })
        this.comments = res.data.data.records
        this.commentPage.total = res.data.data.total
      } catch (error) {
        this.$message.error('获取评论失败')
      }
    },

    async submitComment() {
      if (!this.checkLogin()) return

      if (!this.commentContent.trim()) {
        this.$message.warning('请输入评论内容')
        return
      }

      try {
        const res = await this.$http.post('/api/posts/comment', {
          postId: this.currentPost.id,
          content: this.commentContent
        },
            {
              headers: {
                'Content-Type': 'application/json' // 设置请求头
              }
            })

        if (res.data.code === 200) {
          this.$message.success('评论成功')
          this.commentContent = ''
          this.currentPost.commentCount++
          await this.fetchComments()
        }
      } catch (error) {
        this.$message.error('评论失败')
      }
    },

    handleCommentPageChange(page) {
      this.commentPage.current = page
      this.fetchComments()
    },

    checkLogin() {
      if (!localStorage.getItem('user')) {
        this.$message.warning('请先登录')
        this.$router.push('/login')
        return false
      }
      return true
    },

    formatDateTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },

    handleImageError(post) {
      console.error('图片加载失败:', {
        imageUrl: post.imageUrl,
        fullUrl: window.location.origin + post.imageUrl
      });
    }
  }
}
</script>

<style scoped>
.post-list {
  padding: 20px;
}

.post-item {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.post-header {
  margin-bottom: 10px;
}

.username {
  font-weight: bold;
  margin-right: 10px;
}

.time {
  color: #999;
  font-size: 12px;
}

.post-content {
  margin-bottom: 15px;
  line-height: 1.6;
}

.post-actions {
  display: flex;
  gap: 10px;
}

.comment-form {
  margin-bottom: 20px;
}

.comment-list {
  margin-top: 20px;
}

.comment-item {
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.comment-user {
  font-weight: bold;
  margin-bottom: 5px;
}

.comment-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.post-image {
  margin: 10px 0;
  max-height: 300px;
  overflow: hidden;
}

.post-image .el-image {
  max-width: 100%;
  max-height: 300px;
  border-radius: 4px;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}

.image-error i {
  font-size: 30px;
  margin-bottom: 10px;
}
</style>